/**
 * @文件名称: TaskCache.java
 * @类路径:   com.dssrz.weibo4j.task
 * @描述:     TODO
 * @作者:     robin
 * @时间:     2012-3-13 下午05:18:46
 * @版本:     1.0.0
 */
package com.dssrz.weibo4j.task;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @类功能说明: 所有任务列表
 * @类修改者:
 * @修改日期:
 * @修改说明:
 * @作者: robin
 * @创建时间: 2012-3-13 下午05:18:46
 * @版本: 1.0.0
 */

public class TaskCache {

	public static Map<String, List<Task>> tasks;

	/**
	 * @方法说明:
	 * @参数: @param accessToken
	 * @参数: @param publishtask
	 * @return void
	 * @throws
	 */
	public static void addOneTask(String accessToken, PublishTask publishtask) {
		if (null == tasks) {
			tasks = new HashMap<String, List<Task>>();
		}
		List<Task> tsk = tasks.get(accessToken);
		if (null == tsk) {
			tsk = new ArrayList<Task>();
		}
		tsk.add(publishtask);
		tasks.put(accessToken, tsk);
		doSort();
	}

	/**
	 * @方法说明:按任务执行时间升序排序
	 * @参数:
	 * @return void
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	private static void doSort() {
		if (null == tasks) {
			return;
		}
		Iterator it = tasks.entrySet().iterator();
		while (it.hasNext()) {
			Entry entry = (Entry) it.next();
			List<Task> tsk = (List<Task>) entry.getValue();
			Collections.sort(tsk, new Comparator<Task>() {
				public int compare(Task t1, Task t2) {
					return t1.getBeginExceuteTime().compareTo(
							t2.getBeginExceuteTime());
				}

			});
		}
	}

	/**
	 * @方法说明: 去除过期任务
	 * @参数:     
	 * @return    void
	 * @throws
	 */
	@SuppressWarnings("unchecked")
	public static void removeExpiredTask() {
		if (null == tasks) {
			return;
		}
		Iterator it = tasks.entrySet().iterator();
		while (it.hasNext()) {
			Entry entry = (Entry) it.next();
			List<Task> tsk = (List<Task>) entry.getValue();
			int len = tsk.size();
			for(Task t : tsk) {
				Date excuteTime = t.getBeginExceuteTime();
				Date now = new Date();
				long expiredTime = now.getTime() - excuteTime.getTime();
				if(expiredTime > 30000) {	// 超过30秒
					tsk.remove(t);
				}
			}
			
		}
	}

	/**
	 * @方法说明: 
	 * @参数:     @param accessToken
	 * @参数:     @return
	 * @return    Object
	 * @throws
	 */
	public static List<Task> getTasks(String accessToken) {
		if(null == tasks) {
			return null;
		}
		return tasks.get(accessToken);
	}

}
